package org.gdstash.ui.select;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.*;

public class StrLenDocFilter extends DocumentFilter {
    private int maxLen;

    public StrLenDocFilter(final int len) {
        this.maxLen = len;
    }

    @Override
    public void insertString(final FilterBypass fb, final int offset, final String string, final AttributeSet attr) {
        if (this.accept(fb, offset, 0, string)) {
            try {
                super.insertString(fb, offset, string, attr);
            } catch (BadLocationException ex) {
            }
        }
    }

    @Override
    public void replace(final FilterBypass fb, final int offset, final int length, final String text, final AttributeSet attrs) {
        if (this.accept(fb, offset, length, text)) {
            try {
                super.replace(fb, offset, length, text, attrs);
            } catch (BadLocationException ex) {
            }
        }
    }

    protected boolean accept(final FilterBypass fb, final int offset, final int length, final String str) {
        if (str == null) {
            return true;
        }
        final int strLen = str.length();
        final int textLen = fb.getDocument().getLength();
        boolean valid = false;
        if (strLen + textLen - length <= this.maxLen && strLen + offset <= this.maxLen) {
            valid = true;
        }
        if (!valid) {
            Toolkit.getDefaultToolkit().beep();
        }
        return valid;
    }
}
